package JZ_Offer.dataStructure.list;

import base.ListNode;

/**
 * 删除链表中重复的结点
 * <p>
 * 在一个排序的链表中，存在重复的结点，请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。
 * <p>
 * 例如，链表1->2->3->3->4->4->5 处理后为 1->2->5
 */
public class JZ76_删除链表中重复的结点 {

    private static ListNode deleteDuplication(ListNode pHead) {
        ListNode pre = null;
        ListNode cur = pHead;

        while (cur != null && cur.next != null) {
            if (cur.next.val == cur.val) {
                ListNode node = cur;
                while (node.next != null && node.val == node.next.val) {
                    node = node.next;
                }
                node = node.next;

                if (pre == null) {
                    pHead = node;
                } else {
                    pre.next = node;
                }
                cur = node;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }

        return pHead;
    }

    public static void main(String[] args) {
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        ListNode a3 = new ListNode(3);
        ListNode a4 = new ListNode(3);
        ListNode a5 = new ListNode(4);
        ListNode a6 = new ListNode(4);
        ListNode a7 = new ListNode(5);
        a1.next = a2;
        a2.next = a3;
        a3.next = a4;
        a4.next = a5;
        a5.next = a6;
        a6.next = a7;

        ListNode listNode = deleteDuplication(a1);
        System.out.println();
    }
}
